
#include <string.h>
#include "queue.h"

// tail point to empty element
// head point to non-empty element

void QueueInit(struct queue_t *queue, uint8_t *buf, uint32_t size)
{
	queue->data = buf;
	queue->size = size;
	queue->head = 0;
	queue->tail = 0;
}

static int QueueIsFull(struct queue_t *queue)
{
	if ((queue->tail + 1) % queue->size == queue->head) {
		return 1;
	} else {
		return 0;
	}
}

static int QueueIsEmpty(struct queue_t *queue)
{
	if (queue->head == queue->tail) {
		return 1;
	} else {
		return 0;
	}
}

int QueueEnQueue(struct queue_t *queue, const uint8_t *data)
{
	if (QueueIsFull(queue)) {
		return 1;
	} else {
		memcpy(queue->data + queue->tail, data, sizeof(*data));
		queue->tail = (queue->tail + 1) % queue->size;
		return 0;
	}
}

int QueueDeQueue(struct queue_t *queue, uint8_t *data)
{
	if (QueueIsEmpty(queue)) {
		return 1;
	} else {
		memcpy(data, queue->data + queue->head, sizeof(*data));
		queue->head = (queue->head + 1) % queue->size;
		return 0;
	}
}
